package route

import (
	"fmt"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/bean/httpBean"
	"gitee.com/gitee-go/core/bean/oauthBean"
	"gitee.com/gitee-go/core/common"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/server/service"
	"gitee.com/gitee-go/utils"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"time"
)

type LoginController struct{}

func (LoginController) GetPath() string {
	return "/api/login"
}
func (c *LoginController) Routes(g gin.IRoutes) {
	g.POST("/info", c.info)
	g.POST("/getParam", c.getParam)
	g.POST("/login", utils.GinReqParseJson(c.login))
}
func (LoginController) info(c *gin.Context) {
	rt := &httpBean.LgInfoRes{}
	usr, ok := service.CurrUserCache(c)
	if ok {
		rt.Login = true
		rt.Id = fmt.Sprintf("%d", usr.Id)
		rt.Name = usr.Name
		rt.Nick = usr.Nick
		rt.Avatar = usr.Avatar
		rt.LoginTime = usr.LoginTime.Format(common.TimeFmt)
		rt.RegTime = usr.CreateTime.Format(common.TimeFmt)
	}
	core.NewUIResOk(rt).ResJson(c)
}
func (LoginController) login(c *gin.Context, m *httpBean.LoginReq) {
	if m.Name == "" || m.Pass == "" {
		core.NewUIRes(common.UICodeErrParam).
			ResJson(c)
		return
	}
	usr, ok := service.FindUserName(m.Name)
	if !ok {
		core.NewUIRes(common.UICodeErr).
			SetMsgf("not found user").
			ResJson(c)
		return
	}
	if usr.Pass != utils.Md5String(m.Pass) {
		core.NewUIRes(common.UICodeErr).
			SetMsgf("password err").
			ResJson(c)
		return
	}
	key := comm.MainCfg.ServerConf.LoginKey
	if key == "" {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs("未设置login-key").
			ResJson(c)
		return
	}
	token, err := utils.CreateToken(jwt.MapClaims{
		"uid": fmt.Sprintf("%d", usr.Id),
	}, key, time.Hour*24*5)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	core.NewUIResOk(&httpBean.LoginRes{
		Token:         token,
		Id:            fmt.Sprintf("%d", usr.Id),
		Name:          usr.Name,
		Nick:          usr.Nick,
		Avatar:        usr.Avatar,
		LastLoginTime: usr.LoginTime.Format(common.TimeFmt),
	}).ResJson(c)

	usr.LoginTime = time.Now()
	comm.DBMain.GetDB().Cols("login_time").Where("id=?", usr.Id).Update(usr)
}

func (LoginController) getParam(c *gin.Context) {
	par := &oauthBean.ParamOAuth{}
	err := service.GetsParam(oauthBean.ParamOAuthKey, par)
	if err != nil {
		core.NewUIRes(common.UICodeErrs).
			SetMsgObjs(err).
			ResJson(c)
		return
	}
	m := map[string]string{}
	info, a := par.DefAppInfo()
	_ = a
	urls := ""
	switch info {
	case common.SourceGitee:
		urls = "gitee.com"
	}
	m["source"] = info
	m["host"] = urls
	core.NewUIResOk(m).ResJson(c)
}
